#!/usr/bin/env python3
"""
智能运维诊断脚本
生成时间: 2025-07-15T11:21:55.692128
Playbook: 智能运维诊断_20250715_112155
"""

import subprocess
import json
import sys
import os
from datetime import datetime

def run_ansible_playbook(playbook_path, inventory_path=None):
    """运行Ansible Playbook"""
    try:
        ansible_cmd = ["ansible-playbook", playbook_path]
        if inventory_path:
            ansible_cmd.extend(["-i", inventory_path])
        
        print(f"执行命令: {' '.join(ansible_cmd)}")
        result = subprocess.run(ansible_cmd, capture_output=True, text=True, timeout=600)
        
        return {
            "success": result.returncode == 0,
            "stdout": result.stdout,
            "stderr": result.stderr,
            "returncode": result.returncode
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "error": "执行超时",
            "returncode": -1
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "returncode": -1
        }

def main():
    """主函数"""
    print("=== 智能运维诊断开始 ===")
    print(f"时间: {datetime.now().isoformat()}")
    
    # Kylin配置
    kylin_config = {
  "server": "kylin-server:8080",
  "username": "admin",
  "timeout": 300,
  "retry_count": 3
}
    
    # 执行Ansible Playbook
    playbook_path = "智能运维诊断_20250715_112155.yml"
    result = run_ansible_playbook(playbook_path)
    
    # 输出结果
    print("\n=== 执行结果 ===")
    if result["success"]:
        print("✅ 执行成功")
        print("输出:")
        print(result["stdout"])
    else:
        print("❌ 执行失败")
        print("错误:")
        print(result.get("error", result["stderr"]))
    
    # 保存结果到文件
    playbook_name = "智能运维诊断_20250715_112155"
    output_file = f"{playbook_name}_result.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump({
            "playbook_name": playbook_name,
            "execution_time": datetime.now().isoformat(),
            "result": result,
            "kylin_config": kylin_config
        }, f, ensure_ascii=False, indent=2)
    
    print(f"\n结果已保存到: {output_file}")
    print("=== 智能运维诊断完成 ===")
    
    return 0 if result["success"] else 1

if __name__ == "__main__":
    sys.exit(main())
